import pygame
import random
import math

# 初始化
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("演化：果实与领地")
clock = pygame.time.Clock()

# 颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
BLACK = (0, 0, 0)
ORANGE = (255, 165, 0)

# 玩家类
class Player:
    def __init__(self, x, y, color, is_player=True):
        self.x = x
        self.y = y
        self.color = color
        self.is_player = is_player
        self.speed = 3
        self.attack = 10
        self.defense = 10
        self.learning = 10
        self.health = 100
        self.bullets = []
        self.shoot_cooldown = 0
        self.defending = False
        self.territory = pygame.Rect(x - 50, y - 50, 100, 100)  # 初始领地
        self.alive = True

    def draw(self):
        if not self.alive:
            return
        # 角色本体
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 15)
        # 显示属性
        font = pygame.font.SysFont(None, 16)
        text = font.render(f"A:{self.attack} D:{self.defense} L:{self.learning}", True, WHITE)
        screen.blit(text, (self.x - 30, self.y - 30))

    def move(self, dx, dy):
        if not self.alive:
            return
        self.x = max(15, min(WIDTH - 15, self.x + dx * self.speed))
        self.y = max(15, min(HEIGHT - 15, self.y + dy * self.speed))
        # 更新领地位置
        self.territory.center = (self.x, self.y)

    def shoot(self, target_x, target_y):
        if self.shoot_cooldown > 0 or not self.alive:
            return
        angle = math.atan2(target_y - self.y, target_x - self.x)
        self.bullets.append([self.x, self.y, math.cos(angle) * 7, math.sin(angle) * 7])
        self.shoot_cooldown = 20  # 射击冷却

    def defend(self):
        self.defending = True

    def update(self):
        if not self.alive:
            return
        # 冷却
        if self.shoot_cooldown > 0:
            self.shoot_cooldown -= 1
        # 子弹移动
        for b in self.bullets[:]:
            b[0] += b[2]
            b[1] += b[3]
            if b[0] < 0 or b[0] > WIDTH or b[1] < 0 or b[1] > HEIGHT:
                self.bullets.remove(b)
        # 解除防御
        self.defending = False

    def draw_bullets(self):
        for b in self.bullets:
            pygame.draw.circle(screen, self.color, (int(b[0]), int(b[1])), 3)

# 果实类
class Fruit:
    def __init__(self):
        self.x = random.randint(50, WIDTH - 50)
        self.y = random.randint(50, HEIGHT - 50)
        self.types = [
            {"name": "攻击果实", "attack": 5, "defense": 0, "learning": 0, "req": (10, 5, 5), "color": RED},
            {"name": "防御果实", "attack": 0, "defense": 5, "learning": 0, "req": (5, 10, 5), "color": BLUE},
            {"name": "智慧果实", "attack": 0, "defense": 0, "learning": 5, "req": (5, 5, 10), "color": GREEN},
            {"name": "进化果实", "attack": 3, "defense": 3, "learning": 3, "req": (12, 12, 12), "color": YELLOW},
        ]
        self.type = random.choice(self.types)

    def draw(self):
        pygame.draw.circle(screen, self.type["color"], (self.x, self.y), 10)
        font = pygame.font.SysFont(None, 14)
        screen.blit(font.render("?", True, BLACK), (self.x - 5, self.y - 5))

# 检查是否可以拾取果实
def can_pick_fruit(player, fruit):
    req = fruit.type["req"]
    return player.attack >= req[0] and player.defense >= req[1] and player.learning >= req[2]

# 检查是否可以侵略
def can_invade(attacker, defender):
    if not defender.alive:
        return False
    total_att = attacker.attack + attacker.defense + attacker.learning
    total_def = defender.attack + defender.defense + defender.learning
    return total_att > total_def * 1.2  # 需要高出20%

# 显示文本
def draw_text(text, x, y, color=WHITE):
    font = pygame.font.SysFont(None, 24)
    surface = font.render(text, True, color)
    screen.blit(surface, (x, y))

# 主游戏函数
def main():
    player = Player(WIDTH // 3, HEIGHT // 2, RED, is_player=True)
    ai = Player(2 * WIDTH // 3, HEIGHT // 2, BLUE, is_player=False)
    players = [player, ai]

    fruits = []
    fruit_spawn_timer = 0
    game_over = False
    winner = None

    running = True
    while running:
        dt = clock.tick(60)
        screen.fill((20, 20, 30))

        # 生成果实
        fruit_spawn_timer += 1
        if fruit_spawn_timer >= 300:  # 每5秒生成一个
            fruits.append(Fruit())
            fruit_spawn_timer = 0

        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        if game_over:
            draw_text(f"游戏结束！{winner} 获胜！", WIDTH//2 - 100, HEIGHT//2)
            draw_text("按 R 重新开始", WIDTH//2 - 80, HEIGHT//2 + 40)
            keys = pygame.key.get_pressed()
            if keys[pygame.K_r]:
                main()  # 重启游戏
            pygame.display.flip()
            continue

        # 玩家输入
        keys = pygame.key.get_pressed()
        dx, dy = 0, 0
        if keys[pygame.K_LEFT]:
            dx -= 1
        if keys[pygame.K_RIGHT]:
            dx += 1
        if keys[pygame.K_UP]:
            dy -= 1
        if keys[pygame.K_DOWN]:
            dy += 1
        player.move(dx, dy)

        # 鼠标射击
        if pygame.mouse.get_pressed()[0]:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            player.shoot(mouse_x, mouse_y)

        if keys[pygame.K_SPACE]:
            player.defend()

        # AI 行为（简化）
        for p in players:
            if not p.is_player and p.alive:
                # AI 移动（随机）
                if random.random() < 0.02:
                    p.move(random.choice([-1, 0, 1]), random.choice([-1, 0, 1]))
                # AI 射击（如果看到玩家）
                if random.random() < 0.01:
                    target = player if player.alive else None
                    if target:
                        p.shoot(target.x, target.y)
                # AI 防御（血量低时）
                if p.health < 50 and random.random() < 0.05:
                    p.defend()

            p.update()

        # 拾取果实
        for fruit in fruits[:]:
            for p in players:
                if not p.alive:
                    continue
                dist = math.hypot(p.x - fruit.x, p.y - fruit.y)
                if dist < 25 and can_pick_fruit(p, fruit):
                    p.attack += fruit.type["attack"]
                    p.defense += fruit.type["defense"]
                    p.learning += fruit.type["learning"]
                    fruits.remove(fruit)
                    print(f"{p} 拾取了 {fruit.type['name']}!")

        # 检查侵略
        if can_invade(player, ai) and player.territory.colliderect(ai.territory) and ai.alive:
            if random.random() < 0.1:  # 概率触发
                if random.random() < 0.7:  # 70% 成功
                    ai.alive = False
                    print("玩家成功侵略！")
                else:
                    player.attack = max(5, player.attack - 5)
                    player.defense = max(5, player.defense - 5)
                    player.learning = max(5, player.learning - 5)
                    print("侵略失败，属性下降！")

        # 子弹伤害
        for p in players:
            if not p.alive:
                continue
            for b in player.bullets[:]:
                for enemy in players:
                    if enemy.is_player == p.is_player or not enemy.alive:
                        continue
                    if math.hypot(b[0] - enemy.x, b[1] - enemy.y) < 15:
                        damage = 10
                        if enemy.defending:
                            damage //= 2
                        enemy.health -= damage
                        if b in player.bullets:
                            player.bullets.remove(b)
                        if enemy.health <= 0:
                            enemy.alive = False

        # 绘制
        for fruit in fruits:
            fruit.draw()

        for p in players:
            p.draw()
            p.draw_bullets()

        # 绘制领地
        for p in players:
            if p.alive:
                pygame.draw.rect(screen, (*p.color, 50), p.territory, 2)

        # 检查胜利
        if not ai.alive:
            game_over = True
            winner = "玩家"
        elif not player.alive:
            game_over = True
            winner = "AI"

        # UI
        draw_text(f"生命: {player.health}", 10, 10)
        draw_text(f"果实剩余: {len(fruits)}", 10, 40)

        pygame.display.flip()

    pygame.quit()

if __name__ == "__main__":
    main()